//
//  Card.m
//  Guazi
//
//  Created by koolearn on 11-6-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import <sqlite3.h>
#import "Card.h"
#import "DBConnection.h"
#import "Statement.h"
#import "GuaziAppDelegate.h"



@implementation Card

@synthesize cardId;
@synthesize name;
@synthesize company;
@synthesize address;
@synthesize postcode;
@synthesize position;
@synthesize mobile;
@synthesize tel;
@synthesize fax;
@synthesize email;
@synthesize userId;
@synthesize user;


+ (Card*)cardWithJsonDictionary:(NSDictionary*)dic
{
    return [[[Card alloc] initWithJsonDictionary:dic] autorelease];
}


+ (Card*)cardWithStatement:(Statement*)stmt
{
    return [[[Card alloc] initWithStatement:stmt] autorelease];
}


- (id) initWithJsonDictionary:(NSDictionary*)dic
{
    if ( dic == nil ) return nil;
    self = [super init];
    if ( self ) {
        self.cardId = (([dic objectForKey:@"id"]==[NSNull null]) ? 0 : [[dic objectForKey:@"id"] longLongValue]);
        self.name = ( ([dic objectForKey:@"name"]==[NSNull null]) ? @"" : [dic objectForKey:@"name"] );
        self.company = ( ([dic objectForKey:@"company"]==[NSNull null]) ? @"" : [dic objectForKey:@"company"] );
        self.address = ( ([dic objectForKey:@"address"]==[NSNull null]) ? @"" : [dic objectForKey:@"address"] );
        self.postcode = ( ([dic objectForKey:@"postcode"]==[NSNull null]) ? @"" : [dic objectForKey:@"postcode"] );
        self.position = ( ([dic objectForKey:@"position"]==[NSNull null]) ? @"" : [dic objectForKey:@"position"] );
        self.mobile = ( ([dic objectForKey:@"mobile"]==[NSNull null]) ? @"" : [dic objectForKey:@"mobile"] );
        self.tel = ( ([dic objectForKey:@"tel"]==[NSNull null]) ? @"" : [dic objectForKey:@"tel"] );
        self.fax = ( ([dic objectForKey:@"fax"]==[NSNull null]) ? @"" : [dic objectForKey:@"fax"] );
        self.email = ( ([dic objectForKey:@"email"]==[NSNull null]) ? @"" : [dic objectForKey:@"email"] );
        self.userId = ([dic objectForKey:@"userId"]==[NSNull null] ? 0 : [[dic objectForKey:@"userId"] longLongValue]);
        self.user = nil;
    }
    return self;
}


- (id) initWithStatement:(Statement*)stmt
{
    self = [super init];
    if ( self ) {
        self.cardId = [stmt getInt64:0];
        self.userId = [stmt getInt64:1];
        self.name = [stmt getString:2];
        self.company = [stmt getString:3];
        self.position = [stmt getString:4];
        self.mobile = [stmt getString:5];
        self.address = [stmt getString:6];
        self.tel = [stmt getString:7];
        self.fax = [stmt getString:8];
        self.postcode = [stmt getString:9];
        self.email = [stmt getString:10];
    }
    return self;
}


+ (Card*) cardWithId:(long long)cardId
{
	return [self loadDB:cardId];
}


+ (Card*)cardWithCard:(Card*)card
{
    Card* c = [[[Card alloc] init] autorelease];
    c.cardId = card.cardId;
    c.userId = card.userId;
    c.user = card.user;
    c.name = card.name;
    c.company = card.company;
    c.address = card.address;
    c.postcode = card.postcode;
    c.position = card.position;
    c.mobile = card.mobile;
    c.tel = card.tel;
    c.fax = card.fax;
    c.email = card.email;
    return c;
}


- (void)setValuesFromCard:(Card*)card
{
    self.name = card.name;
    self.company = card.company;
    self.address = card.address;
    self.postcode = card.postcode;
    self.position = card.position;
    self.mobile = card.mobile;
    self.tel = card.tel;
    self.fax = card.fax;
    self.email = card.email;
}



- (User*) user
{
    if ( userId > 0 && user==nil ) {
        self.user = [User userWithId:userId];
    }
    return user;
}


- (NSString*) toString
{
    NSString* s = [NSString stringWithFormat:@"{cardId:'%lld', name:'%@', company:'%@', position:'%@', mobile:'%@', address:'%@', tel:'%@', fax:'%@', postcode:'%@', email:'%@'}", cardId, name, company, position, mobile, address, tel, fax, postcode, email];
    return s;
}


#pragma mark - 数据库操作


+ (NSArray*) cardsForUser:(long long)auserId
{
    sqlite3* database = [DBConnection getDatabase];
    char* sql = "select id, user_id, name, company, position, mobile, address, tel, fax, postcode, email from cards where user_id = ? ";
    Statement* stmt = [[Statement alloc] initWithDB:database sql:sql];
    [stmt bindInt64:auserId forIndex:1];
    
    NSMutableArray* array = [NSMutableArray array];
    while ( [stmt step]==SQLITE_ROW ) {
        [array addObject:[Card cardWithStatement:stmt]];
    }
    [stmt release];
    return array;
}


- (void) updateDB
{
    sqlite3* database = [DBConnection getDatabase];
    char* sql = "replace into cards (id, user_id, name, company, position, mobile, address, tel, fax, postcode, email) values (?,?,?,?,?,?,?,?,?,?,?)";
    
    Statement* stmt = [[Statement alloc] initWithDB:database sql:sql];
    [stmt bindInt64:cardId forIndex:1];
    [stmt bindInt64:userId forIndex:2];
    [stmt bindString:name forIndex:3];
    [stmt bindString:company forIndex:4];
    [stmt bindString:position forIndex:5];
    [stmt bindString:mobile forIndex:6];
    [stmt bindString:address forIndex:7];
    [stmt bindString:tel forIndex:8];
    [stmt bindString:fax forIndex:9];
    [stmt bindString:postcode forIndex:10];
    [stmt bindString:email forIndex:11];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        NSAssert2( 0, @"Fail to prepare statement: %s (%s)", sql, sqlite3_errmsg(database) );
    }
    else {
        [stmt release];
    }
}


- (void) deleteDB
{
    sqlite3* database = [DBConnection getDatabase];
    char* sql = "delete from cards where id = ?";
    
    Statement* stmt = [[Statement alloc] initWithDB:database sql:sql];
    [stmt bindInt64:cardId forIndex:1];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        NSAssert2( 0, @"Fail to prepare statement: %s (%s)", sql, sqlite3_errmsg(database) );
    }
    else {
        [stmt release];
    }
}


+ (Card*) loadDB:(long long)cardId
{
    sqlite3* database = [DBConnection getDatabase];
    char* sql = "select id, user_id, name, company, position, mobile, address, tel, fax, postcode, email from cards where id = ?";
    
    Statement* stmt = [[Statement alloc] initWithDB:database sql:sql];
    [stmt bindInt64:cardId forIndex:1];
	
	Card* card = nil;
	if ( [stmt step] == SQLITE_ROW ) {
		card = [Card cardWithStatement:stmt];
	}
	
	[stmt release];
	return card;
}


+ (void) deleteAllCards:(long long)userId
{
    sqlite3* database = [DBConnection getDatabase];
    char* sql = "delete from cards where user_id = ?";
    
    Statement* stmt = [[Statement alloc] initWithDB:database sql:sql];
    [stmt bindInt64:userId forIndex:1];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        NSAssert2( 0, @"Fail to prepare statement: %s (%s)", sql, sqlite3_errmsg(database) );
    }
    else {
        [stmt release];
    }
}


+ (void) setCardsForUser:(long long)userId cards:(NSArray*)cards
{
    [self deleteAllCards:userId];
    
    if ( cards == nil || [cards count] == 0 ) return;
    
    for ( Card* card in cards ) {
        [card updateDB];
    }
}



- (void) dealloc
{
    [name release];
    [company release];
    [address release];
    [postcode release];
    [position release];
    [mobile release];
    [tel release];
    [fax release];
    [email release];
    [user release];
    [super dealloc];
}


@end
